import subprocess

from PySide6.QtCore import QTimer, Qt
from PySide6.QtWidgets import QMainWindow, QWidget, QSizePolicy, QDialog

from kvm import Kvm
from main_window_ui import Ui_MainWindow
from player import PlayThread
from setting_ui import Ui_Dialog


class SettingDialog(QDialog):
    def __init__(self, conf):
        super(SettingDialog, self).__init__()
        self.ui = Ui_Dialog()  # UI类的实例化
        self.ui.setupUi(self)


class MainWindow(QMainWindow):
    def __init__(self, conf):
        super(MainWindow, self).__init__()
        self.conf = conf
        self.ui = Ui_MainWindow()  # UI类的实例化
        self.ui.setupUi(self)
        self.ui.toolBar.hide()
        self.kvm = Kvm(self.conf)
        self.ui.gridLayout.addWidget(self.kvm, 0, 0, 1, 1)
        self.kvm.close_signal.connect(self.close)
        self.kvm.toolbar_signal.connect(self.toolbar_toggle)

        spacer = QWidget(self.ui.toolBar)
        spacer.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.ui.toolBar.addWidget(spacer)
        self.ui.toolBar.addAction(self.ui.actionPlay)
        self.ui.toolBar.addAction(self.ui.actionRecord)
        self.ui.toolBar.addAction(self.ui.actionStop)
        spacer = QWidget(self.ui.toolBar)
        spacer.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.ui.toolBar.addWidget(spacer)

        self.ui.toolBar.addAction(self.ui.actionSetting)
        self.ui.actionSetting.triggered.connect(self.settings)

        self.ui.toolBar.addAction(self.ui.actionPower)
        self.ui.actionPower.triggered.connect(self.poweroff)

        self.player = None
        self.dialog = SettingDialog(self.conf)

    def toolbar_toggle(self, key: Qt.Key):
        if key == Qt.Key.Key_F11:
            if self.ui.toolBar.isHidden():
                self.ui.toolBar.show()
            else:
                self.ui.toolBar.hide()
        elif key == Qt.Key.Key_F1:
            self.kvm.recorder.start()
        elif key == Qt.Key.Key_F2:
            self.kvm.recorder.stop()
        elif key == Qt.Key.Key_F3:
            self.player = PlayThread(self.kvm.ch9329, "track/20241222160120.track")
            self.player.start()
        elif key == Qt.Key.Key_F4:
            if self.player is not None:
                self.player.stop()

    def closeEvent(self, event):
        if not self.kvm.video_thread_finished:
            self.kvm.stop()
            event.ignore()

    def settings(self):
        self.dialog.show()
        self.dialog.setWindowFlags(self.dialog.windowFlags | Qt.WindowType.WindowStaysOnTopHint)

    @staticmethod
    def poweroff():
        subprocess.call(["poweroff"])

